package com.android.tianyuanyouxuan.ui.activity;

import android.content.Intent;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.recyclerview.widget.LinearLayoutManager;

import com.android.tianyuanyouxuan.base.BaseActivity;
import com.android.tianyuanyouxuan.bean.Goods;
import com.android.tianyuanyouxuan.databinding.ActivitySearchBinding;
import com.android.tianyuanyouxuan.presenter.SearchPresenter;
import com.android.tianyuanyouxuan.ui.adapter.SearchAdapter;
import com.blankj.utilcode.util.GsonUtils;
import com.chad.library.adapter.base.BaseQuickAdapter;
import com.chad.library.adapter.base.listener.OnItemClickListener;

import java.util.List;


public class SearchActivity extends BaseActivity {

    private ActivitySearchBinding viewBinding;

    private SearchPresenter presenter = new SearchPresenter();
    private SearchAdapter adapter = new SearchAdapter();

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        viewBinding = ActivitySearchBinding.inflate(LayoutInflater.from(this));
        setContentView(viewBinding.getRoot());
        initTitleBar();
        viewBinding.rvList.setLayoutManager(new LinearLayoutManager(this));
        viewBinding.rvList.setAdapter(adapter);
        searchGoods();
        viewBinding.tvSearch.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                searchGoods();
            }
        });
        adapter.setOnItemClickListener(new OnItemClickListener() {
            @Override
            public void onItemClick(@NonNull BaseQuickAdapter<?, ?> adapter1, @NonNull View view, int position) {
                Intent intent = new Intent(SearchActivity.this, GoodsDetailsActivity.class);
                Goods goods = adapter.getItem(position);
                intent.putExtra("data", GsonUtils.toJson(goods));
                startActivity(intent);
            }
        });

    }

    private void searchGoods() {
        List<Goods> list = presenter.getGoodsList(TextUtils.isEmpty(viewBinding.etSearch.getText()) ? "" : viewBinding.etSearch.getText().toString());
        adapter.setNewInstance(list);
    }

}
